﻿using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.WriteAPI.Applications.Commands.MeetingReservations;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.Meeting.WriteAPI.Applications.CommandHandlers.MeetingReservations
{
    public class AddReservationCommandHandler : IRequestHandler<AddReservationCommand, APIResult<int>>
    {
        IBaseRepository<MeetingReservation> mrtRep;
        ILogger<AddReservationCommandHandler> logger;

        public AddReservationCommandHandler(IBaseRepository<MeetingReservation> mrtRep, ILogger<AddReservationCommandHandler> logger)
        {
            this.mrtRep = mrtRep;
            this.logger = logger;
        }

        public async Task<APIResult<int>> Handle(AddReservationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 检查请求参数是否有效
                if (request.Data == null || string.IsNullOrWhiteSpace(request.Data.ThemeName))
                {
                    logger.LogWarning("会议预约数据无效或主题名称为空");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "会议预约数据无效或主题名称为空",
                        Data = 0
                    };
                }

                // 检查是否已存在同名会议预约
                var existingRoom = await mrtRep.GetAll().FirstOrDefaultAsync(r => r.ThemeName == request.Data.ThemeName, cancellationToken);
                if (existingRoom != null)
                {
                    logger.LogWarning($"会议主题 '{request.Data.ThemeName}' 已存在");
                    return new APIResult<int>
                    {
                        Code = StatusEnumCode.Fail,
                        Message = "会议主题已存在",
                        Data = 0
                    };
                }

                // 添加到数据库
                await mrtRep.AddAsync(request.Data);

                logger.LogInformation($"成功添加会议主题: {request.Data.ThemeName} (ID: {request.Data.MeetingReservationId})");

                // 返回成功结果
                return new APIResult<int>
                {
                    Code = StatusEnumCode.Ok,
                    Message = "添加会议预约成功",
                    Data = 1
                };
            }
            catch (Exception ex)
            {
                logger.LogError("添加会议预约失败", ex.Message);
                throw;
            }
        }
    }
}
